﻿using e_commerce.BLL.Manager.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using e_commerce.BLL.Data;
using e_commerce.BLL.Models;

namespace e_commerce.BLL.Services.Client
{
    public class OrderService : IOrderClientApplicationService,IDisposable
    {
        private commerceDbContext _dbContext;
        private GoodsManager _goodsManager;
        private AccountService _accountService;
        public OrderService()
        {
            _dbContext = new commerceDbContext();
            _goodsManager = new GoodsManager();
            _accountService = new AccountService();
        }

        public void AddGoodsToShoppingCart(int goodsId, int customerId, int count = 1)
        {
            var goods = _goodsManager.GetGoodsById(goodsId);
            var customer = _accountService.GetClient(customerId);
            var sCart = new ShoppingCart()
            {
                ClientId = customerId,
                CreateTime = DateTime.Now,
                Number = count,
                Client = customer,
                GoodsInfo = goods,
            };
            _dbContext.ShoppingCart.Add(sCart);
            SaveChanges();
        }

        private string GetNowTime()
        {
            string NowYear = DateTime.Now.ToString("yyyy");
            string NowMouth = DateTime.Now.ToString("MM");
            string NowDay = DateTime.Now.ToString("dd");
            if (NowMouth.Length == 1)
            {
                NowMouth = "0" + NowMouth;
            }
            if (NowDay.Length == 1)
            {
                NowDay = "0" + NowDay;
            }
            string NowTime = NowYear + NowMouth + NowDay;
            return NowTime;
        }

        public void ApplyRefundByOrderId(string orderId)
        {
            var order = GetOrderById(orderId);
            order.State = (int)OrderState.ApplyRefund;
            SaveChanges();
        }

        public void ApplyReturnByOrderId(string orderId)
        {
            var order = GetOrderById(orderId);
            order.State = (int)OrderState.ApplyReturn;
            SaveChanges();
        }

        public void CancleOrderByOrderId(string orderId)
        {
            var order = GetOrderById(orderId);
            order.State = (int)OrderState.CanselOrder;
            var goods = _dbContext.GoodsInfo.SingleOrDefault(g => g.GoodsId == order.GoodsId);
            if(goods == null)
            {
                throw new Exception("未查询到该商品");
            }
            goods.Stock++;
            SaveChanges();
        }

        public void ConfirmOrderByOrderId(string orderId)
        {
            var order = GetOrderById(orderId);
            order.State = (int)OrderState.OrderOver;
            SaveChanges();
        }

        public string GetOrderState(OrderState state)
        {
            string result = string.Empty;
            switch (state)
            {
                case OrderState.Unpaid: result = "待付款"; break;
                case OrderState.Untreated: result = "未处理"; break;
                case OrderState.Noship: result = "未发货"; break;
                case OrderState.Noreceived: result = "未收货"; break;
                case OrderState.OrderOver: result = "订单已完成"; break;
                case OrderState.ApplyRefund: result = "申请退款中"; break;
                case OrderState.OnRefund: result = "已退款"; break;
                case OrderState.ApplyReturn: result = "申请退货"; break;
                case OrderState.OnReturn: result = "已退货"; break;
                case OrderState.CanselOrder: result = "订单已取消"; break;
                default: result = "订单状态异常"; break;
            }
            return result;
        }
        public string CreateOrder(Order order)
        {
            lock (_goodsManager)
            {
                Random rnd = new Random();
                var goods = _goodsManager.GetGoodsById(order.GoodsId);
                if (goods.Stock - order.Count < 0)
                {
                    throw new Exception("该商品库存不足，订单创建失败");
                }
                var newOrder = order;
                newOrder.CreateTime = DateTime.Now;
                newOrder.OrderId = GetNowTime() + rnd.Next(10000, 99999);
                newOrder.State = (int)OrderState.Unpaid;
                _dbContext.Order.Add(newOrder);
                SaveChanges();
                return newOrder.OrderId;
            }
        }

        public void Payment(string orderId,int clientId,string password)
        {
            var order = GetOrderById(orderId);
            var client = _dbContext.Client.SingleOrDefault(c => c.ClientId == clientId);
            if(client == null)
            {
                throw new Exception("用户状态异常");
            }
            if(order.State == (int)OrderState.Untreated)
            {
                throw new Exception("操作异常");
            }
            if(client.PayPassword != password)
            {
                throw new Exception("用户支付密码错误");
            }
            decimal total = (decimal)order.Price * order.Count;
            if(client.Wallet.CompareTo( total) < 0)
            {
                throw new Exception("余额不足，无法支付");
            }
            client.Wallet -= total;
            order.PaymentTime = DateTime.Now;
            order.State = (int)OrderState.Untreated;
            SaveChanges();
        }
        public void DeleteGoodsToShppingCart(int goodsId, int customerId)
        {
            var sCart = _dbContext.ShoppingCart.SingleOrDefault(sc => sc.GoodsInfo.GoodsId == goodsId && sc.ClientId == customerId);
            _dbContext.ShoppingCart.Remove(sCart);
            SaveChanges();
        }

        public void Dispose()
        {
            _dbContext.Dispose();
        }

        public void SaveChanges()
        {
            _dbContext.SaveChanges();
        }

        public void EvaluateOrder(Comment comment)
        {
            var newComment = comment;
            newComment.CommentTime = DateTime.Now;
            _dbContext.Comment.Add(newComment);
            SaveChanges();
        }
        public Order GetOrderById(string orderId)
        {
            var order = _dbContext.Order.SingleOrDefault(o => o.OrderId.Equals(orderId));
            if(order == null)
            {
                throw new Exception("订单不存在");
            }
            return order;
        }

        public IEnumerable<Order> GetOrderByState(int clientId,int state)
        {
            var client = _dbContext.Client.SingleOrDefault(c => c.ClientId == clientId);
            if(client == null)
            {
                throw new Exception("用户异常");
            }
            var orders = state == 0?
                _dbContext.Order.OrderByDescending(o=>o.CreateTime).Where(o=>o.ClientId == clientId && !o.IsDelete)
                : _dbContext.Order.OrderByDescending(o => o.CreateTime).Where(o => o.ClientId == clientId && o.State == state&&!o.IsDelete);
            return orders;
        }
        public void ModifyGoodsCountFromShoppintCart(int customerId, int goodsId, int count)
        {
            var sCart = _dbContext.ShoppingCart.SingleOrDefault(sc => sc.GoodsInfo.GoodsId == goodsId && sc.ClientId == customerId);
            sCart.Number = count;
            SaveChanges();
        }

        public void PayByOrderId(string orderId)
        {
            var order = GetOrderById(orderId);
            var customer = _dbContext.Client.SingleOrDefault(c => c.ClientId == order.ClientId);
            if(customer == null)
            {
                throw new Exception("该用户不存在");
            }
            //
        }

        public IEnumerable<Order> GetClientOrderById(int clientId,int page,int size)
        {
            var order = _dbContext.Order.Where(o => o.ClientId == clientId)
                .Skip((page - 1) * size)
                .Take(size);
            return order;
        }

        public IEnumerable<Order> GetClientAllOrderById(int clientId)
        {
            return _dbContext.Order.OrderByDescending(o=>o.CreateTime).Where(o => o.ClientId == clientId);
        }
    }
}
